import datetime

from webapp.extensions import AppException
from webapp.models import VBorrowInfo, BorrowInfo, db


class BorrowInfoService:

    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        start_time = kwargs.get('start')
        resourceId = kwargs.get('resname')
        rtype = kwargs.get('rtype')
        query = []
        if resourceId:
            query.append(VBorrowInfo.resourceId == resourceId)
        if rtype:
            query.append(VBorrowInfo.rtype == rtype)

        if start_time and len(start_time) >= 2:
            query.append((VBorrowInfo.start.between(start_time[0], start_time[1])))
        if create_times and len(create_times) >= 2:
            query.append((VBorrowInfo.create_time.between(create_times[0], create_times[1])))
        result = VBorrowInfo.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                           error_out=False)
        return result

    @staticmethod
    def create(curr_borrow: BorrowInfo):
        coursetable: BorrowInfo = BorrowInfo.query.filter(BorrowInfo.id == curr_borrow.id).one_or_none()
        if coursetable:
            raise AppException(f'{curr_borrow.ename}已存在!')
        curr_borrow.create_time = datetime.datetime.now()
        borrowInfoTable = BorrowInfo(
            start=curr_borrow.start,
            end=curr_borrow.end,
            total=curr_borrow.total,
            status=curr_borrow.status,
            borrower=curr_borrow.borrower,
            resourceId=curr_borrow.resourceId,
            create_time=curr_borrow.create_time,
            create_by=curr_borrow.create_by
        )
        db.session.add(borrowInfoTable)
        db.session.commit()

    @staticmethod
    def find_by_id(id):
        borrowInfotable = db.session.query(BorrowInfo).filter(BorrowInfo.id == id).one_or_none()
        if borrowInfotable is None:
            raise AppException(f'您所操作的对象已不存在!')
        return borrowInfotable

    @staticmethod
    def delete(borrow_set):
        if borrow_set:
            for borrowId in borrow_set:
                db.session.delete(borrowId)
            db.session.commit()

    @staticmethod
    def update(curr_borrow: BorrowInfo):
        borrowInfotable = BorrowInfo.query.filter(BorrowInfo.id == curr_borrow.id).one_or_none()
        if borrowInfotable is None:
            raise AppException(f'修改的数据可能已不存在!')
        borrowInfotable.resourceId = curr_borrow.resourceId
        borrowInfotable.total = curr_borrow.total
        borrowInfotable.status = curr_borrow.status
        borrowInfotable.borrower = curr_borrow.borrower
        borrowInfotable.start = curr_borrow.start
        borrowInfotable.end = curr_borrow.end
        borrowInfotable.update_time = datetime.datetime.now()
        borrowInfotable.update_by = curr_borrow.update_by
        db.session.commit()